package com.esayread.reader

import android.content.Context
import android.util.Log
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
import org.json.JSONObject

/**
 * 管理阅读进度的类
 * 使用SharedPreferences以JSON的形式持久化每本书的阅读进度
 */
class ReadingProgressManager(private val context: Context) {

    companion object {
        private const val TAG = "ReadingProgressManager"
        private const val PREFS_NAME = "reading_progress_prefs"
        private const val KEY_PROGRESS_MAP = "progress_map"
    }

    /**
     * 保存阅读进度
     * @param bookPath 书籍文件的绝对路径（作为键）
     * @param chapterIndex 当前章节索引
     * @param chapterPosition 当前章节内位置（像素/偏移/字符位置，取决于调用方约定）
     * @param globalPosition 全书内的全局字符位置
     * @param totalCharacters 全书的总字符数
     */
    suspend fun saveProgress(
        bookPath: String,
        chapterIndex: Int,
        chapterPosition: Int,
        globalPosition: Int,
        totalCharacters: Int
    ) = withContext(Dispatchers.IO) {
        try {
            val prefs = context.getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE)
            val current = prefs.getString(KEY_PROGRESS_MAP, "{}") ?: "{}"
            val root = JSONObject(current)

            val progressObj = JSONObject().apply {
                put("chapterIndex", chapterIndex)
                put("chapterPosition", chapterPosition)
                put("globalPosition", globalPosition)
                put("totalCharacters", totalCharacters)
            }

            root.put(bookPath, progressObj)
            prefs.edit().putString(KEY_PROGRESS_MAP, root.toString()).apply()
            Log.d(TAG, "Saved progress for $bookPath: chapter=$chapterIndex, pos=$chapterPosition, global=$globalPosition/$totalCharacters")
        } catch (e: Exception) {
            Log.e(TAG, "Failed to save progress: ${e.message}", e)
        }
    }

    /**
     * 获取阅读进度
     * @param bookPath 书籍文件的绝对路径
     * @return ReadingProgress 或 null
     */
    suspend fun getProgress(bookPath: String): ReadingProgress? = withContext(Dispatchers.IO) {
        try {
            val prefs = context.getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE)
            val current = prefs.getString(KEY_PROGRESS_MAP, null) ?: return@withContext null
            val root = JSONObject(current)
            if (!root.has(bookPath)) return@withContext null

            val obj = root.getJSONObject(bookPath)
            val chapterIndex = obj.optInt("chapterIndex", 0)
            val chapterPosition = obj.optInt("chapterPosition", 0)
            val globalPosition = obj.optInt("globalPosition", 0)
            val totalCharacters = obj.optInt("totalCharacters", 0)

            return@withContext ReadingProgress(
                chapterIndex = chapterIndex,
                chapterPosition = chapterPosition,
                globalPosition = globalPosition,
                totalCharacters = totalCharacters
            )
        } catch (e: Exception) {
            Log.e(TAG, "Failed to get progress: ${e.message}", e)
            null
        }
    }
}

/**
 * 阅读进度数据
 */
data class ReadingProgress(
    val chapterIndex: Int,
    val chapterPosition: Int,
    val globalPosition: Int,
    val totalCharacters: Int
) {
    val progressPercentage: Int
        get() = if (totalCharacters > 0) {
            ((globalPosition.toFloat() / totalCharacters) * 100).toInt().coerceIn(0, 100)
        } else 0
}